import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { removeToken } from '@/utils/auth'

// create an axios instance
// 创建了一个axios实例对象
// console.log(process.env, 1122)
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    if (res.success) {
      // Message({
      //   message: res.message || 'Error',
      //   type: 'success',
      //   duration: 5 * 1000
      // })
      return res
    } else {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  (error) => {
    // console.dir('err===' + error.response.data.code)
    // 当响应状态码是10002时token失效清除cookie里的token和vuex里的token并跳转到登录页面
    if (error.response.data.code === 10002) {
      removeToken()
      // console.log(store)
      // 打印出store里面有commit函数,通过mutations清空里面的token
      store.commit('user/SET_TOKEN', '')

      // js页面不能使用Vue通过导入使用
      router.push('/login')

      // 原生的API里面有一个localtion对象里面有个reload可以刷新页面
      // console.log(window)
      window.location.reload()
    }
    return Promise.reject(error)
  }
  // (error) => {
  //   console.log('err' + error) // for debug
  //   Message({
  //     message: error.message,
  //     type: 'error',
  //     duration: 5 * 1000
  //   })
  //   return Promise.reject(error)
  // }
)

export default service
